package ynu.edu.order.listener;


import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import ynu.edu.common.exception.BadRequestException;
import ynu.edu.order.service.IOrderService;

import java.io.IOException;

@Component
@RequiredArgsConstructor
@Slf4j
public class PayStatusListener {

    private final IOrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "trade.pay.success.queue", durable = "true"),
            exchange = @Exchange(name = "pay.topic"),
            key = "pay.success"
    ))
    public void listenPaySuccess(String message, Channel channel,
                                 @Header(AmqpHeaders.DELIVERY_TAG) long tag) {

        log.info("[PayStatusListener] 收到消息: {}", message);

        try {
            Long orderId = Long.valueOf(message);
//            orderService.markOrderPaySuccess(orderId);
            handleAck(channel, tag);
        } catch (BadRequestException e) {
            log.warn("业务校验失败，直接丢弃消息", e);
            handleNack(channel, tag, false);
        } catch (Exception e) {
            log.error("系统异常，稍后重试", e);
            handleNack(channel, tag, true);
        }
    }

    // 统一处理消息确认（Ack）
    private void handleAck(Channel channel, long tag) {
        try {
            if (channel.isOpen()) {
                channel.basicAck(tag, false);
                log.debug("[PayStatusListener] 消息确认成功, tag: {}", tag);
            } else {
                log.warn("[PayStatusListener] 通道已关闭，无法确认消息, tag: {}", tag);
            }
        } catch (IOException e) {
            log.error("[PayStatusListener] 确认消息失败, tag: {}", tag, e);
        }
    }

    // 统一处理消息拒绝（Nack）
    private void handleNack(Channel channel, long tag, boolean requeue) {
        try {
            if (channel.isOpen()) {
                channel.basicNack(tag, false, requeue);
                log.debug("[PayStatusListener] 消息拒绝成功, tag: {}, requeue: {}", tag, requeue);
            } else {
                log.warn("[PayStatusListener] 通道已关闭，无法拒绝消息, tag: {}", tag);
            }
        } catch (IOException e) {
            log.error("[PayStatusListener] 拒绝消息失败, tag: {}", tag, e);
        }
    }

}